package com.fowo.api.service.handleWork;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fowo.api.costAccounting.mapper.CommonCostingMapper;
import com.fowo.api.costAccounting.model.bd.BdAccperiodmonthVo;
import com.fowo.api.costAccounting.service.CostAccountingService;
import com.fowo.api.costAccounting.service.impl.CostAccountingServiceImpl;
import com.fowo.api.datainterface.util.k3cloud.domain.Authentication;
import com.fowo.api.datainterface.util.k3cloud.domain.BillSave;
import com.fowo.api.entity.*;
import com.fowo.api.model.sales.outbound.SalesOutboundShopPushAction;
import com.fowo.api.model.sales.outbound.log.SalesOutboundLogVo;
import com.fowo.api.service.handleWork.jindieEntity.jindieResult;
import com.fowo.api.service.handleWork.jindieEntity.jindieVoucher2;
import com.fowo.api.service.impl.SalesOutboundLogServiceImpl;
import com.fowo.api.service.impl.SalesOutboundServiceImpl;
import com.fowo.api.service.impl.ShopInfoServiceImpl;
import com.fowo.api.util.LocalDateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class SalesOutboundShopPush implements SalesOutboundShopPushAction {

    @Resource
    private SalesOutboundServiceImpl salesOutboundService;
    private static final Authentication auth=new Authentication("64e8964fb4af0d","Administrator","a@123456");

    private static final K3CloudTemplate k3loudTemplate=new K3CloudTemplate("http://121.225.97.82:8001/K3cloud/",auth);
    @Resource
    private ShopInfoServiceImpl shopInfoService;
//    @Resource
//    private AccountingPeriodServiceImpl AccountingPeriodService;
    @Resource
    private SalesOutboundLogServiceImpl alesOutboundLogService;
    @Autowired
    private CommonCostingMapper commonCostingMapper;

    @Override
    public synchronized void run() throws Exception {
        //获取当前会计月
//        AccountingPeriod accountingPeriod = CostAccountingService.getOne(Wrappers.<AccountingPeriod>query().lambda().eq(AccountingPeriod::getStatus, "1"));
        List<BdAccperiodmonthVo> bdAccperiodmonthVoList = commonCostingMapper.getByStatus();
        if(bdAccperiodmonthVoList.size()==0||bdAccperiodmonthVoList.size()>1){
            throw new Exception("会计月份查出多条或没有符合得数据");
        }
        BdAccperiodmonthVo bdAccperiodmonthVo = bdAccperiodmonthVoList.get(0);
        List<SalesOutbound> list = salesOutboundService.list(Wrappers.<SalesOutbound>query().lambda()
                .eq(SalesOutbound::getAccountType,"Standard")
                .eq(SalesOutbound::getEventType,"Shipment")
                .eq(SalesOutbound::getType,"Principal")
                .isNotNull(SalesOutbound::getLocalSku)
                .ne(SalesOutbound::getLocalSku,"")
                .between(SalesOutbound::getPostedDateLocale,LocalDateUtils.format(bdAccperiodmonthVo.getBeginDate(),LocalDateUtils.DATE_PATTERN)+" 00:00:00",
                        LocalDateUtils.format(bdAccperiodmonthVo.getEndDate(),LocalDateUtils.DATE_PATTERN)+" 23:59:59")
                .groupBy(SalesOutbound::getSid));


        for(int i=0;i<list.size();i++){
            SalesOutbound salesOutbound = list.get(i);
            try{
                tuisong(bdAccperiodmonthVo, salesOutbound);
            }catch (Exception e){

            }
        }
    }

    private synchronized void tuisong(BdAccperiodmonthVo accountingPeriod, SalesOutbound salesOutbound) throws Exception {

        List<SalesOutboundLog> list2 = alesOutboundLogService.list(Wrappers.<SalesOutboundLog>query().lambda()
                .eq(SalesOutboundLog::getReportFormsMonthly, LocalDateUtils.format(salesOutbound.getPostedDateLocale(), LocalDateUtils.DATE_PATTERN1))
                .eq(SalesOutboundLog::getShopName, salesOutbound.getSid()+"")
        );
        Assert.isTrue(list2.size()==0,"已经推送了");

        SalesOutboundLogVo model=new SalesOutboundLogVo();
        model.setShopName(salesOutbound.getSid()+"");
        model.setReportFormsMonthly(LocalDateUtils.format(salesOutbound.getPostedDateLocale(), LocalDateUtils.DATE_PATTERN1));
        model.setPushStatus("推送失败");
        Long aLong = alesOutboundLogService.create(model);
        model.setId(aLong);

        QueryWrapper<SalesOutbound> queryWrapper=new QueryWrapper();
        queryWrapper.select("local_sku,sum(current_issue_cost_amount) as  current_issue_cost_amount,quantity");
        queryWrapper.eq("sid",salesOutbound.getSid());
        queryWrapper.eq("account_type","Standard");
        queryWrapper.eq("event_type","Shipment");
        queryWrapper.isNotNull("local_sku");
        queryWrapper.isNotNull("current_issue_cost_amount");
        queryWrapper.eq("type","Principal");
        queryWrapper.between("posted_date_locale", LocalDateUtils.format(accountingPeriod.getBeginDate(),LocalDateUtils.DATE_PATTERN)+" 00:00:00",LocalDateUtils.format(accountingPeriod.getEndDate(),LocalDateUtils.DATE_PATTERN)+" 23:59:59");
        queryWrapper.groupBy("local_sku");
        List<SalesOutbound> list1 = salesOutboundService.list(queryWrapper);
        //查询关联的店铺信息
        ShopInfo one = shopInfoService.getOne(Wrappers.<ShopInfo>query().lambda().eq(ShopInfo::getShopCode, salesOutbound.getSid()));
        Assert.notNull(one,"店铺信息不存在!");
        Assert.isTrue(one.getJindieShopCode()!=null,"店铺没有绑定金蝶的店铺编码!");
        String bumen="";
        String shiyebu="";
        //判断是义乌还是深圳
        if(salesOutbound.getSellerName().contains("深圳")){
            shiyebu="SYB01";
            bumen="BM000024";
        }else{
            shiyebu="SYB02";
            bumen="BM000023";
        }
        pushJinDie1(salesOutbound,list1, bumen, shiyebu,one,model);
    }

    private void pushJinDie1(SalesOutbound salesOutbound, List<SalesOutbound> list1,String bumen,String shiyebu, ShopInfo shopInfo,SalesOutboundLogVo model) throws Exception {
        //获取日期
        int month = salesOutbound.getPostedDateLocale().getMonth()+1;
        String yuefen=month+"月份";
        //所有sku的价格
        BigDecimal reduce = list1.stream().filter(x->x.getCurrentIssueCostAmount()!=null&&x.getQuantity()!=null).map(SalesOutbound::getCurrentIssueCostAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
//        BigDecimal reduce =new BigDecimal("100");
        BillSave billSave = new BillSave("GL_VOUCHER");
        jindieVoucher2 jindieVoucher=new  jindieVoucher2();
        jindieVoucher.setIsAutoAdjustField("true");
        jindieVoucher.setIsEntryBatchFill("true");
        jindieVoucher.setNumberSearch("true");
        jindieVoucher.setIsControlPrecision("false");
        jindieVoucher2.ModelDTO  modelDTO=new jindieVoucher2.ModelDTO();
        modelDTO.setFvoucherid(0);
        //账簿
        jindieVoucher2.ModelDTO.FAccountBookIDDTO FAccountBookIDDTO=new  jindieVoucher2.ModelDTO.FAccountBookIDDTO();
        FAccountBookIDDTO.setFNumber("002");
        modelDTO.setFAccountBookID(FAccountBookIDDTO);
        //日期
        modelDTO.setFDate(LocalDateUtils.format(salesOutbound.getPostedDateLocale(),LocalDateUtils.DATE_PATTERN));
//        modelDTO.setFDate("2023-03-31");
        //凭证字
        jindieVoucher2.ModelDTO.FVOUCHERGROUPIDDTO FVOUCHERGROUPIDDTO=new jindieVoucher2.ModelDTO.FVOUCHERGROUPIDDTO();
        FVOUCHERGROUPIDDTO.setFNumber("PRE001");
        modelDTO.setFvouchergroupid(FVOUCHERGROUPIDDTO);
        modelDTO.setFvouchergroupno("1");
        modelDTO.setFDocumentStatus("Z");
        List<jindieVoucher2.ModelDTO.FEntityDTO> list=new ArrayList<>();
        jindieVoucher2.ModelDTO.FEntityDTO entity = createEntity("6401.01",reduce.doubleValue(),null,shiyebu,bumen,shopInfo.getJindieShopCode(),shopInfo.getJindieShopCode(),yuefen,reduce,shopInfo);
        list.add(entity);
        jindieVoucher2.ModelDTO.FEntityDTO entity1 = createEntity("1405.01",null,reduce.doubleValue(),null,null,null,shopInfo.getJindieShopCode(),yuefen,reduce,shopInfo);
        list.add(entity1);

        modelDTO.setFEntity(list);
        jindieVoucher.setModel(modelDTO);
        Map<String, Object> stringObjectMap = BeanUtil.beanToMap(jindieVoucher, false, false);
        billSave.setModel(stringObjectMap);
        String result = k3loudTemplate.executeBillSave(billSave, String.class);
        jindieResult jindieResult = JSONObject.parseObject(result, jindieResult.class);
        if(!jindieResult.getResult().getResponseStatus().getIsSuccess().equals("true")){
            Assert.isTrue(false,"推送失败:"+jindieResult.getResult().getResponseStatus().getErrors().get(0).getMessage());

        }else{
            model.setPushStatus("推送完成");
            alesOutboundLogService.update(model);
        }
    }


    private static jindieVoucher2.ModelDTO.FEntityDTO createEntity(String kemu,
                                                                   Double jiefang,
                                                                   Double daifang,
                                                                   String shiyebu,
                                                                   String bumen,
                                                                   String dianpu,
                                                                   String code,
                                                                   String yuefen,
                                                                   BigDecimal yuanbi,
                                                                   ShopInfo shopInfo
    ){
        jindieVoucher2.ModelDTO.FEntityDTO fEntityDTO=new jindieVoucher2.ModelDTO.FEntityDTO();
        //科目编码
        jindieVoucher2.ModelDTO.FEntityDTO.FACCOUNTIDDTO FACCOUNTIDDTO=new jindieVoucher2.ModelDTO.FEntityDTO.FACCOUNTIDDTO();
        FACCOUNTIDDTO.setFNumber(kemu);
        fEntityDTO.setFaccountid(FACCOUNTIDDTO);
        //店铺名称
        fEntityDTO.setFexplanation(shopInfo.getShopName()+yuefen+"销售成本");
        //币别
        jindieVoucher2.ModelDTO.FEntityDTO.FCURRENCYIDDTO  FCURRENCYIDDTO=new jindieVoucher2.ModelDTO.FEntityDTO.FCURRENCYIDDTO();
        FCURRENCYIDDTO.setFNumber("PRE001");//PRE001
        fEntityDTO.setFcurrencyid(FCURRENCYIDDTO);
        //汇率
        jindieVoucher2.ModelDTO.FEntityDTO.FEXCHANGERATETYPEDTO FEXCHANGERATETYPEDTO=new jindieVoucher2.ModelDTO.FEntityDTO.FEXCHANGERATETYPEDTO();
        FEXCHANGERATETYPEDTO.setFNumber("HLTX01_SYS");
        fEntityDTO.setFexchangeratetype(FEXCHANGERATETYPEDTO);
        fEntityDTO.setFexchangerate(0.0);
        fEntityDTO.setFamountfor(yuanbi.doubleValue());
            if(kemu.equals("1122.01")&&jiefang<0){
                fEntityDTO.setFcredit(new BigDecimal(jiefang).abs().doubleValue());//
                fEntityDTO.setFamountfor(yuanbi.abs().doubleValue());
            }else {
                fEntityDTO.setFdebit(jiefang);//
                fEntityDTO.setFcredit(daifang);
            }

        jindieVoucher2.ModelDTO.FEntityDTO.FDetailIDDTO FDetailIDDTO=new jindieVoucher2.ModelDTO.FEntityDTO.FDetailIDDTO();
        //事业部
        if(shiyebu!=null){
            jindieVoucher2.ModelDTO.FEntityDTO.FDetailIDDTO.FDETAILIDFF100003DTO  FDETAILIDFFLEX4DTO=new  jindieVoucher2.ModelDTO.FEntityDTO.FDetailIDDTO.FDETAILIDFF100003DTO();
            FDETAILIDFFLEX4DTO.setFNumber(shiyebu);
            FDetailIDDTO.setFDETAILID__FF100003(FDETAILIDFFLEX4DTO);
            fEntityDTO.setFDetailID(FDetailIDDTO);
        }
        //部门
        if(bumen!=null){
            jindieVoucher2.ModelDTO.FEntityDTO.FDetailIDDTO.FDETAILIDFFLEX5DTO  FDETAILIDFFLEX4DTO=new  jindieVoucher2.ModelDTO.FEntityDTO.FDetailIDDTO.FDETAILIDFFLEX5DTO();
            FDETAILIDFFLEX4DTO.setFNumber(bumen);
            FDetailIDDTO.setFDETAILID__FFLEX5(FDETAILIDFFLEX4DTO);
            fEntityDTO.setFDetailID(FDetailIDDTO);
        }
        //店铺
        if(dianpu!=null){
            jindieVoucher2.ModelDTO.FEntityDTO.FDetailIDDTO.FDETAILIDFF100007DTO  FDETAILIDFF100007DTO=new  jindieVoucher2.ModelDTO.FEntityDTO.FDetailIDDTO.FDETAILIDFF100007DTO();
            FDETAILIDFF100007DTO.setFNumber(dianpu);
            FDetailIDDTO.setFDETAILID__FF100007(FDETAILIDFF100007DTO);
            fEntityDTO.setFDetailID(FDetailIDDTO);
        }
        //仓库
        if(kemu.equals("1405.01")){
            jindieVoucher2.ModelDTO.FEntityDTO.FDetailIDDTO.FDETAILIDFF100004DTO  FDETAILIDFF100004DTO=new  jindieVoucher2.ModelDTO.FEntityDTO.FDetailIDDTO.FDETAILIDFF100004DTO();
            FDETAILIDFF100004DTO.setFNumber("CK08");
            FDetailIDDTO.setFDETAILID__FF100004(FDETAILIDFF100004DTO);
            fEntityDTO.setFDetailID(FDetailIDDTO);
        }
        return fEntityDTO;
    }

    //获取币种
    public  String bizhong(String s){
        String str=null;
        //金蝶的币种
        if(s.equals("USD")){
            str="PRE007";
        }else if(s.equals("CAD")){
            str="PRE008";
        }else if(s.equals("MXN")){
            str="PRE009";
        }else if(s.equals("EUR")){
            str="PRE003";
        }else if(s.equals("GBP")){
            str="PRE006";
        }else{
            Assert.isTrue(false,"没有找到这个币种!");
        }
        return  str;

    }

    public  BigDecimal KeepOne(BigDecimal bigDecimal,BigDecimal huilv){
        BigDecimal bigDecimal1 =bigDecimal.multiply(huilv).setScale(2, BigDecimal.ROUND_HALF_UP);
        return bigDecimal1;
    }

}
